package com.otp.service.util;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.Document;


public class DOMElementsFromString {

	public static List<Element> parseString(String str, Document doc){
		
		List<Element> result = new ArrayList<Element>();
		
		//Prepare to parse string
		Integer[] codes = new Integer[100];
		for(int i=0; i<100; i++) codes[i]=0;
		List<String> openTags = new ArrayList<String>();
		List<String> closeTags = new ArrayList<String>();
		openTags.add("<h3>");
		openTags.add("<p>");
		closeTags.add("</h3>");
		closeTags.add("</p>");
		
		//Parse string for paragraphs
		List<String> substrings = HTMLTagParsing.parseHTML(str, openTags, closeTags, codes);
		
		Element Paragraph;
		for(int i=0; i<substrings.size(); i++){
		//Paragraph Element
			if (codes[i]==0||codes[i]==2){
				Integer[] subCodes = new Integer[100];
				for(int j=0; j<100; j++) subCodes[j]=0;
				openTags.clear();
				closeTags.clear();
				openTags.add("<b>");
				openTags.add("<i>");
				closeTags.add("</b>");
				closeTags.add("</i>");
				
				List<String> subPStrings = HTMLTagParsing.parseHTML(substrings.get(i), openTags, closeTags, subCodes);

				Paragraph=doc.createElement("pTest");
				//Paragraph.appendChild(doc.createTextNode(subPStrings.get(j)));
				Element subPar;
				
				if(subPStrings.size()==0) System.out.println("String list is empty!!!!");
				for(int j=0; j<subPStrings.size(); j++){
					if(subPStrings.get(j)==null||subPStrings.get(j)=="") System.out.println("String is empty!!!");

					subPar = doc.createElement("subP");
					subPar.appendChild(doc.createTextNode(subPStrings.get(j)));
					switch (subCodes[j]){
					case 0: subPar.setAttribute("format", "none"); break;
					case 1: subPar.setAttribute("format", "bold"); break;
					case 2: subPar.setAttribute("format", "italics"); break;
					case 3: subPar.setAttribute("format", "bold_and_italics"); break;
					}
					Paragraph.appendChild(subPar);
				}//end subParagraph list
				result.add(Paragraph);
//				Chapter.appendChild(Paragraph);
			}
			//Header (3) Element
			if (codes[i]==1||codes[i]==3){
				Paragraph=doc.createElement("h3");
				Paragraph.appendChild(doc.createTextNode(substrings.get(i)));
				result.add(Paragraph);
//				Chapter.appendChild(Paragraph);					
			}
		}
		
		return result;		
	}//end method
	
}
